package com.cold.demo.es;

import com.cold.demo.es.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.*;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;


@SpringBootApplication
public class EsSpringbootApplication implements ApplicationListener<ContextStartedEvent> {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(EsSpringbootApplication.class, args);
    }


    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    @PostConstruct
    public void init() {
        String  indexName       = "user";
        boolean existsIndexUser = elasticsearchRestTemplate.indexExists(indexName);
        if (!existsIndexUser) {
            // 创建索引
            boolean user = elasticsearchRestTemplate.createIndex(indexName);
            System.out.println(user);
        }
        System.out.println();

        String id = "1610012687610";

        GetQuery getQuery = new GetQuery();
        getQuery.setId(id);
        User        user1       = elasticsearchRestTemplate.queryForObject(getQuery, User.class);


        Criteria    criteria    = new Criteria();
        CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
        criteriaQuery.setIds(Collections.singleton(id));
        List<User>          user          = elasticsearchRestTemplate.queryForList(criteriaQuery, User.class);
        System.out.println();

    }



    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        System.out.println();
    }
}
